package com.wakala.employment.fragment.finder;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.cityjd.JDCityConfig;
import com.lljjcoder.style.cityjd.JDCityPicker;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.stx.xmarqueeview.XMarqueeView;
import com.wakala.employment.R;
import com.wakala.employment.adapter.ItemClickListener;
import com.wakala.employment.adapter.JobInfoListAdapter;
import com.wakala.employment.adapter.base.broccoli.BroccoliSimpleDelegateAdapter;
import com.wakala.employment.adapter.bean.JobInfoPage;
import com.wakala.employment.adapter.bean.JobInfoSearchRequest;
import com.wakala.employment.adapter.entity.JobInfoVo;
import com.wakala.employment.adapter.jobCategory.JobCategoryTreeVo;
import com.wakala.employment.adapter.marquee.MarqueeViewAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentJobListBinding;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.CategoryMenuVo;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link JobListFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none,name = "JobListFragment")
public class JobListFragment extends BaseFragment<FragmentJobListBinding> implements View.OnClickListener {

    private static String TAG = JobListFragment.class.getSimpleName();

    private BroccoliSimpleDelegateAdapter<JobInfoVo> mJobsAdapter;
    private List<JobInfoVo> jobInfoVoList = new ArrayList<>();
    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;
    private JobInfoListAdapter mJobInfoListAdapter;

    private ArrayList<String> tagLayoutTags = new ArrayList<>();
    private ArrayList<JobCategoryTreeVo> selectedJobList = new ArrayList<>();

    int currentPage = 1;
    int pageSize = 10;


    /**
     * jonInfo查询条件
     */
    private JobInfoSearchRequest jobInfoSearchRequest = new JobInfoSearchRequest();


    @NonNull
    @Override
    protected FragmentJobListBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentJobListBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        StatusBarUtils.setStatusBarLightMode(getActivity());
        return null;
    }

    @Override
    protected void initViews() {
        initWeChatTip();
        recyclerView = binding.recyclerView;
        refreshLayout = binding.refreshLayout;
        // 初始化RecyclerView
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 20);
        binding.recyclerView.setRecycledViewPool(viewPool);
        WidgetUtils.initRecyclerView(recyclerView, DensityUtils.dp2px(getContext(), 5), ThemeUtils.resolveColor(getContext(), R.attr.xui_config_color_background));

        recyclerView.setAdapter(mJobInfoListAdapter = new JobInfoListAdapter(false,recyclerViewItemClickListener));
        //

    }

    /**
     * recyclerView item点击事件
     */
    private final ItemClickListener<JobInfoVo> recyclerViewItemClickListener = new ItemClickListener<JobInfoVo>() {

        @Override
        public void onItemClick(RecyclerViewHolder holder, View view, JobInfoVo model, int position) {
            openNewPage(JobInfoFragment.class, "jobInfoId", model.getId());
        }
    };



    private void initWeChatTip(){
        List<String> data = new ArrayList<>();
        data.add("免费加入本地招人找活群");
        data.add("附件找人找活信息推送");
        data.add("优质创业项目推荐");
        data.add("超多赚钱机会分享");

        XMarqueeView xMarqueeView = (XMarqueeView)findViewById(R.id.marquee);
        try {
            xMarqueeView.setAdapter(new MarqueeViewAdapter(data, getContext()));
        } catch (Exception e) {
            Log.w("", e.getMessage());
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==Constants.REQ_RESULT_110){//工种选择
            selectedJobList = data.getParcelableArrayListExtra("selectedJobList");
            tagLayoutTags=data.getStringArrayListExtra("tagLayoutTags");
            String kindText = "";
            for(String tagText:tagLayoutTags){
                kindText+=tagText+"、";
            }
            if(tagLayoutTags.size()>1){
                binding.ssBtnWorkKinds.setText(tagLayoutTags.get(0)+"-等"+tagLayoutTags.size()+"个");
            }else{
                if(tagLayoutTags.isEmpty()){
                    binding.ssBtnWorkKinds.setText("所有工种");
                }else {
                    binding.ssBtnWorkKinds.setText(tagLayoutTags.get(0));
                }

            }

            StringBuilder jobCategoryIds = new StringBuilder();
            for(JobCategoryTreeVo jobCategoryTreeVo:selectedJobList){
                jobCategoryIds.append(jobCategoryTreeVo.getId()).append(",");
            }
            if(jobCategoryIds.length()>0){
                jobInfoSearchRequest.setJobCategoryId(jobCategoryIds.toString());
                getJobInfoList("fresh");
            }

        }
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        //获取传递过来的参数
        Object obj = getArguments().get("data");
        if(null!=obj && obj instanceof  CategoryMenuVo){
            CategoryMenuVo categoryMenuVo = (CategoryMenuVo)obj;
            if(categoryMenuVo.getTarget()==1){
                //1---目标--》工种
                if(!categoryMenuVo.getJobCategoryNames().isEmpty()){
                    if(categoryMenuVo.getJobCategoryNames().size()>1){
                        //binding.ssBtnWorkKinds.setText(categoryMenuVo.getJobCategoryNames().get(0)+"-等"+categoryMenuVo.getJobCategoryNames().size()+"个工种");
                    }else {
                        //binding.ssBtnWorkKinds.setText(categoryMenuVo.getJobCategoryNames().get(0));
                    }
                    //显示菜单名称
                    binding.ssBtnWorkKinds.setText(categoryMenuVo.getName());
                    //设置菜单配置的工种ID值，形式为：独立或逗号分隔的工种id 例如：工种id+“，”+工种id
                    jobInfoSearchRequest.setJobCategoryId(categoryMenuVo.getUrl());
                    //getJobInfoList("fresh");
                }
            }else if(categoryMenuVo.getTarget()==2){
                //2----目标--》职位标签
                binding.tvKeywords.setText(categoryMenuVo.getUrl());
                jobInfoSearchRequest.setJobTags(categoryMenuVo.getUrl());
            }else if(categoryMenuVo.getTarget()==3){
                //3---->关键字 title关键字，关键字标签
                binding.tvKeywords.setText(categoryMenuVo.getUrl());
                jobInfoSearchRequest.setKeywords(categoryMenuVo.getUrl());
                //getJobInfoList("fresh");
            }

        }
    }


    @Override
    protected void initListeners() {
        super.initListeners();
        binding.ssBtnToBack.setOnClickListener(this);
        binding.tvSearch.setOnClickListener(this);
        binding.ssBtnRegion.setOnClickListener(this);//城市过滤
        binding.ssBtnWorkKinds.setOnClickListener(this);//工种过滤
        binding.rbWeiChat.setOnClickListener(view -> {
            try {

                new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
                    @Override
                    protected int getImplLayoutId() {
                        return R.layout.dialog_invite_view;
                    }

                    @Override
                    protected void onCreate() {
                        super.onCreate();

                    }
                }).show();
            }catch (Exception e){
                Log.e("",e.getMessage());
            }
        });
        //
        initRecycleView();
    }
    private void initRecycleView(){
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                currentPage++;
                jobInfoSearchRequest.setPage(currentPage);
                getJobInfoList("more");
            }

            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                currentPage = 1;
                jobInfoSearchRequest.setPage(currentPage);
                getJobInfoList("fresh");
            }
        });

        mJobInfoListAdapter.setOnItemClickListener((itemView, item, position) -> {
            // Utils.goWeb(getContext(), item.getDetailUrl())
            openNewPage(JobInfoFragment.class, "jobId", item.getJobId());
        });

        //设置刷新加载时禁止所有列表操作
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.autoRefresh();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id==R.id.ssBtn_region){//城市
            showCityPicker();
        } else if (id ==R.id.ssBtn_work_kinds) {//工种
            openPageForResult(JobCategoryFragment.class, Constants.REQ_RESULT_110);
        } else if(id == R.id.ssBtn_toBack){
            popToBack();
        }
    }

    /**
     * 显示省市区选择组件
     */
    private void showCityPicker() {
        //创建对象
        JDCityPicker cityPicker = new JDCityPicker();
        //初始化配置
        JDCityConfig jdCityConfig = new JDCityConfig.Builder().build();
        //设置显示的样式
        jdCityConfig.setShowType(JDCityConfig.ShowType.PRO_CITY);
        cityPicker.init(getContext());//初始化选择器
        cityPicker.setConfig(jdCityConfig);
        cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province,
                                   CityBean city, DistrictBean district) {//选中后的监听
                String cityName = city.getName();
                if (city.getName().equals("市辖区")) {
                    cityName = province.getName();
                }
                binding.ssBtnRegion.setText(cityName);
                //更新求职意向 城市
                jobInfoSearchRequest.setJobProvince(province.getName());
                jobInfoSearchRequest.setJobCityName(city.getName());
                getJobInfoList("fresh");
            }

            @Override
            public void onCancel() {
                //cancel监听
            }
        });
        //显示地区列表
        cityPicker.showCityPicker();
    }

    /**
     * 查询招聘信息列表数据
     *
     * @return
     */
    @SuppressLint("CheckResult")
    private void getJobInfoList(String type) {
        binding.llStateful.showContent();
        if(type.equals("fresh")){
           if(null!=refreshLayout && !refreshLayout.isRefreshing()){
               refreshLayout.autoRefresh();
           }
        }
        jobInfoSearchRequest.setLimit(pageSize);
        XHttpProxy.proxy(TestApi.IJobService.class)
                .jobInfList(jobInfoSearchRequest)
                .subscribeWith(new NoTipRequestSubscriber<JobInfoPage>() {
                    @Override
                    protected void onSuccess(JobInfoPage commonPageApiResult) {
                        Log.i(TAG, "-------------招工信息列表------------------");
                        Log.i(TAG, GsonUtils.toJson(commonPageApiResult));
                        if (type.equals("fresh")) {
                            mJobInfoListAdapter.refresh(commonPageApiResult.getList());
                            refreshLayout.finishRefresh();
                            if(commonPageApiResult.getList().isEmpty()){
                                ToastUtils.toast("暂无相关招工岗位");
                                binding.llStateful.showEmpty("暂无相关招工岗位");
                            }else{
                                binding.llStateful.showContent();
                            }
                        }else if(type.equals("more")){
                            if(commonPageApiResult.getList().isEmpty()){
                                //展示无数据孔状态
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                ToastUtils.toast("已更新到最新数据");
                            }else {
                                mJobInfoListAdapter.loadMore(commonPageApiResult.getList());
                                refreshLayout.finishLoadMore();
                            }

                        }

                        Log.i(TAG, "-------------招工信息列表------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                       // binding.refreshLayout.finishLoadMore();
                        ToastUtils.toast(e.getDisplayMessage());
                       /* binding.llStateful.showError("加载数据失败", "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                getJobInfoList();
                            }
                        });*/
                        Log.i(TAG, "-------------招工信息列表-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });

    }
}